package com.yunshu.yunshuapp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboShareException;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.CommonLoadingView;
import com.yunshu.yunshuapp.zixunlist.ZixunListModel;

import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;


public class WebviewWithShareActivity extends AppCompatActivity implements View.OnClickListener, IWXAPIEventHandler , IWeiboHandler.Response , IUiListener {

    protected String url;
    protected ZixunListModel zixun;
    protected ImageLoader mImageLoader;
    protected IWXAPI api;
    protected IWeiboShareAPI mWeiboShareAPI;
    protected Tencent mTencent;
    protected Boolean qqSharing = false;
    protected CommonLoadingView loadingView;
    protected ImageButton loveBtn;
    protected WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_share);

        NavigationBar navibar = (NavigationBar) findViewById(R.id.navigationBar);
        navibar.putInActivity(this);
        loadingView = (CommonLoadingView) findViewById(R.id.loadingView);

        Bundle bundle = this.getIntent().getExtras();
        url = (String) bundle.get("url");
        String title = (String) bundle.get("title");

        if (title != null){
            navibar.setTitle(title);
        }
        String zixunString = (String) bundle.get("zixun");
        if (zixunString != null){
            ObjectMapper mapper = new ObjectMapper();
            try {
                zixun = mapper.readValue(zixunString, ZixunListModel.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        this.refresh();

        addListener();
        this.updateLoveButton();
        // 使用ImageLoader之前初始化
        YSUtils.initImageLoader(this);

        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
        api = WXAPIFactory.createWXAPI(this, YSUtils.WXAPPID, false);
        api.registerApp(YSUtils.WXAPPID);
        api.handleIntent(getIntent(), this);

        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, YSUtils.WEIBOAPPID);
        mWeiboShareAPI.registerApp();

        mTencent = Tencent.createInstance(YSUtils.QQAPPID, this.getApplicationContext());

    }

    protected void refresh() {
        webView.loadUrl(url);
        webView.setWebViewClient(new HelloWebViewClient ());
    }

    protected void addListener() {
        ImageButton shareTimelineBtn = (ImageButton) findViewById(R.id.timelineBtn);
        shareTimelineBtn.setOnClickListener(this);

        ImageButton btn2 = (ImageButton) findViewById(R.id.weiboBtn);
        btn2.setOnClickListener(this);

        ImageButton btn3 = (ImageButton) findViewById(R.id.wechatBtn);
        btn3.setOnClickListener(this);

        ImageButton btn4 = (ImageButton) findViewById(R.id.qqBtn);
        btn4.setOnClickListener(this);

        ImageButton btn5 = (ImageButton) findViewById(R.id.qzoneBtn);
        btn5.setOnClickListener(this);

        loveBtn = (ImageButton) findViewById(R.id.loveBtn);
        loveBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.timelineBtn){
            this.share2WX(SendMessageToWX.Req.WXSceneTimeline);

        }else if(view.getId() == R.id.weiboBtn){
            this.share2Weibo();
        }else if(view.getId() == R.id.wechatBtn){
            this.share2WX(SendMessageToWX.Req.WXSceneSession);
        }else if(view.getId() == R.id.qqBtn){
            this.share2QQ();
        }else if(view.getId() == R.id.qzoneBtn){
            this.share2QZone();
        }else if(view.getId() == R.id.loveBtn){
            this.loveZixun();
        }
    }

    protected void share2Weibo() {

        if (!mWeiboShareAPI.isWeiboAppInstalled()) {
            Toast.makeText(this, "未安装微博！", Toast.LENGTH_LONG).show();
            return;
        }

        final WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息

        TextObject textObject = new TextObject();
        textObject.text = zixun.getTitle();
        weiboMessage.textObject = textObject;
//        loadingView.setVisibility(View.VISIBLE);
//        loadingView.load();

        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = YSUtils.generateGUID();
        mediaObject.title = zixun.getTitle();
        mediaObject.description = zixun.getTitle();
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = shareURL();
        mediaObject.defaultText = "云数智惠";
        weiboMessage.mediaObject = mediaObject;
        final SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
        request1.transaction = String.valueOf(System.currentTimeMillis());
        request1.multiMessage = weiboMessage;
        qqSharing = false;
        boolean b = mWeiboShareAPI.sendRequest(WebviewWithShareActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//        loadingView.setVisibility(View.VISIBLE);
//        loadingView.load();
//        mImageLoader.loadImage(zixun.getImageUrl(), new ImageLoadingListener() {
//            @Override
//            public void onLoadingStarted(String s, View view) { }
//
//            @Override
//            public void onLoadingFailed(String s, View view, FailReason failReason) {
//                loadingView.setVisibility(View.INVISIBLE);
//                boolean b = mWeiboShareAPI.sendRequest(WebviewWithShareActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//            }
//
//            @Override
//            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                loadingView.setVisibility(View.INVISIBLE);
//
//                WebpageObject mediaObject = new WebpageObject();
//                mediaObject.identify = YSUtils.generateGUID();
//                mediaObject.title = zixun.getTitle();
//                mediaObject.description = zixun.getTitle();
//                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//                float w = bitmap.getWidth();
//                float h = bitmap.getHeight();
//                bitmap = YSUtils.ratio(bitmap,100, 100/w * h);
//                mediaObject.setThumbImage(bitmap);
//                mediaObject.actionUrl = shareURL();
//                mediaObject.defaultText = "云数智惠";
//                weiboMessage.mediaObject = mediaObject;
//                Boolean valiad = weiboMessage.checkArgs();
//                SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
//                request1.transaction = String.valueOf(System.currentTimeMillis());
//                request1.multiMessage = weiboMessage;
//                qqSharing = false;
//                boolean b = mWeiboShareAPI.sendRequest(WebviewWithShareActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//                System.out.println("11111"+b);
//            }
//
//            @Override
//            public void onLoadingCancelled(String s, View view) {
//
//            }
//        });

    }

    protected String shareURL() {
        return url+"&iscome=1";
    }

    protected void share2QQ() {
//        if (!mTencent.is()){
//            Toast.makeText(this, "未安装QQ!", Toast.LENGTH_LONG).show();
//        }
        Bundle bundle = new Bundle();
        //这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        //分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, zixun.getTitle());


        //分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, zixun.getImageUrl());
        //分享的消息摘要，最长50个字
//        bundle.putString(QQShare.PARAM_SUMMARY, "测试");

        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        //标识该消息的来源应用，值为应用名称+AppId。
//        bundle.putString(QQShare.PARAM_APP_SOURCE, "星期几" + YSUtils.QQAPPID);

        bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);

        qqSharing = true;
        mTencent.shareToQQ(this, bundle , this);
    }

    public void share2QZone(){
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);//类型
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, this.zixun.getTitle());//标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, this.zixun.getTitle());//概要
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        if (this.zixun.getImageUrl() != null ) {
            //下面这个必须加上  不然无法调动 qq空间
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add(this.zixun.getImageUrl());
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        }else{
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add("http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        }
        mTencent.shareToQzone(WebviewWithShareActivity.this, params, WebviewWithShareActivity.this);
    }

    protected void share2WX(final int WXScene) {
        if (!api.isWXAppInstalled()){
            Toast.makeText(this, "未安装微信!", Toast.LENGTH_LONG).show();
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = this.shareURL();

        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = zixun.getTitle();
        msg.description = zixun.getDate();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
        req.message = msg;
        req.scene = WXScene;
        qqSharing = false;
//        boolean ret = api.sendReq(req);
        mImageLoader.loadImage(zixun.getImageUrl(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                loadingView.setVisibility(View.INVISIBLE);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                loadingView.setVisibility(View.INVISIBLE);

                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
                float w = bitmap.getWidth();
                float h = bitmap.getHeight();
                bitmap = YSUtils.ratio(bitmap,100, 100/w * h);
                msg.setThumbImage(bitmap);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }

            @Override
            public void onLoadingCancelled(String s, View view) {
                loadingView.setVisibility(View.INVISIBLE);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }
        });

    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                System.out.println("COMMAND_GETMESSAGE_FROM_WX");
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                goToShowMsg((ShowMessageFromWX.Req) req);
                System.out.println("COMMAND_SHOWMESSAGE_FROM_WX");

                break;
            default:
                break;
        }
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(this, "成功分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
            default:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this); //当前应用唤起微博分享后，返回当前应用
    }

    public void onResponse(BaseResponse baseResp) {//接收微客户端博请求的数据。

        switch (baseResp.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, "成功分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, "取消分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this, "分享到微博失败", Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onComplete(Object o) {
        Toast.makeText(this, "成功分享到QQ", Toast.LENGTH_LONG).show();
    }
    public void onError(UiError e) {

        Toast.makeText(this, "分享到QQ失败", Toast.LENGTH_LONG).show();
    }
    public void onCancel() {

        Toast.makeText(this, "取消分享到QQ", Toast.LENGTH_LONG).show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        loadingView.setVisibility(View.INVISIBLE);
        if (null != mTencent && qqSharing)
            mTencent.onActivityResultData(requestCode, resultCode, data , this);
    }

    //Web视图
    protected class HelloWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")){
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
            } else if(url.startsWith("http:") || url.startsWith("https:")) {
                view.loadUrl(url);
            }
            return true;
        }

    }

    protected void loveZixun(){
        final int type = zixun.isLoved(this)? 2:1 ; //点赞
        loadingView.setVisibility(View.VISIBLE);
        new YSRequest(this).GET(YSRequest.ZIXUN_Love,"id="+this.zixun.getModelId()+"&type="+type,new YSCallback(){

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingView.setVisibility(View.INVISIBLE);
                    }
                });
                if(isSuccess == YSRequest.REQUEST_OK){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.setVisibility(View.INVISIBLE);
                            if (type == 1) {
                                zixun.setLoved(true,WebviewWithShareActivity.this);
                                loveBtn.setBackgroundResource(R.mipmap.zixun_love1);
                            }else{
                                zixun.setLoved(false,WebviewWithShareActivity.this);
                                loveBtn.setBackgroundResource(R.mipmap.zixun_love);

                            }
                        }
                    });
                }else{
                    YSUtils.showToastOn(WebviewWithShareActivity.this,"点赞失败，请稍后重试");
                }
            }
        });
    }

    protected void updateLoveButton() {
        if(zixun!=null && zixun.isLoved(this)) {//点赞
            loveBtn.setBackgroundResource(R.mipmap.zixun_love1);
        }
    }

}
